package org.smart4j.charpter2.helper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.collections4.MapUtils;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smart4j.charpter2.util.PropsUtil;

/**
 * 数据库帮助类
 * @author 蒋贵强
 *
 */
public final class DatabaseHelper {

	private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseHelper.class);
	
	private static final String DRIVER;
	private static final String URL;
	private static final String USERNAME;
	private static final String PASSWORD;
	
	private static final ThreadLocal<Connection> CONNECTION_HOLDER=new ThreadLocal<Connection>(); 
	
	private static final BasicDataSource DATA_SOURCE;
	
	private static final QueryRunner QUERY_RUNNER = new QueryRunner();
	
	static{
		Properties conf = PropsUtil.loadProps("jdbc.properties");
		DRIVER = conf.getProperty("jdbc.driver");
		URL = conf.getProperty("jdbc.url");
		USERNAME = conf.getProperty("jdbc.username");
		PASSWORD = conf.getProperty("jdbc.password");
		
		DATA_SOURCE = new BasicDataSource();
		DATA_SOURCE.setDriverClassName(DRIVER);
		DATA_SOURCE.setUrl(URL);
		DATA_SOURCE.setUsername(USERNAME);
		DATA_SOURCE.setPassword(PASSWORD);
		
	}
	
	/**
	 * 获取数据库连接
	 * @return
	 */
	public static Connection getConnection(){
		Connection conn = CONNECTION_HOLDER.get();
		if(conn == null){
			try {
//				conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
				conn = DATA_SOURCE.getConnection();
			} catch (Exception e) {
				LOGGER.error("get connection failure", e);
				throw new RuntimeException(e);
			}finally {
				CONNECTION_HOLDER.set(conn);
			}
		}
		return conn;
	}
	
	/**
	 * 关闭数据库连接
	 */
//	public static void closeConnection(){
//		Connection conn = CONNECTION_HOLDER.get();
//		if(conn!=null){
//			try {
//				conn.close();
//			} catch (SQLException e) {
//				LOGGER.error("close connection error", e);
//				throw new RuntimeException(e);
//			}finally {
//				CONNECTION_HOLDER.remove();
//			}
//		}
//	}
	
	/**
	 * 返回list
	 * @param entityClass
	 * @param sql
	 * @param params
	 * @return
	 */
	public static<T> List<T> queryEntityList(Class<T> entityClass,String sql ,Object... params){
		List<T> entityList = null;
		try{
			Connection conn = getConnection();
			entityList = QUERY_RUNNER.query(conn, sql, new BeanListHandler<T>(entityClass), params);
		}catch(SQLException e){
			LOGGER.error("query Entity List Error!!!!", e);
			throw new RuntimeException(e);
		}finally {
//			closeConnection();
		}
		
		return entityList;
	}
	
	/**
	 * 返回一个实体
	 * @param entityClass
	 * @param sql
	 * @param params
	 * @return
	 */
	public static<T> T queryEntity(Class<T> entityClass,String sql ,Object... params){
		T entity = null;
		try{
			Connection conn = getConnection();
			entity = QUERY_RUNNER.query(conn, sql, new BeanHandler<T>(entityClass), params);
		}catch(SQLException e){
			LOGGER.error("query Entity List Error!!!!", e);
			throw new RuntimeException(e);
		}finally {
//			closeConnection();
		}
		
		return entity;
	}
	
	/**
	 * 执行复杂查询
	 * @param sql
	 * @param params
	 * @return
	 */
	public static List<Map<String,Object>> executeQuery(String sql ,Object... params){
		List<Map<String,Object>> result = null;
		try{
			Connection conn = getConnection();
			result = QUERY_RUNNER.query(conn, sql, new MapListHandler(), params);
		}catch(SQLException e){
			LOGGER.error("query Entity List Error!!!!", e);
			throw new RuntimeException(e);
		}finally {
//			closeConnection();
		}
		
		return result;
	}
	
	/**
	 * 获得表名
	 * @param entityClass
	 * @return
	 */
	private static String getTableName(Class<?> entityClass){
		return entityClass.getSimpleName();
	}
	
	/**
	 * 执行更新语句
	 * @param sql
	 * @param params
	 * @return
	 */
	public static int executeUpdate(String sql ,Object... params){
		int rows = 0;
		try{
			Connection conn = getConnection();
			rows = QUERY_RUNNER.update(conn,sql,params);
		}catch(SQLException e){
			LOGGER.error("execute update Error!!!!", e);
			throw new RuntimeException(e);
		}finally{
//			closeConnection();
		}
		return rows;
	}
	
	/**
	 * 插入实体
	 * @param entityClass
	 * @param fieldMap
	 * @return
	 */
	public static<T> boolean insertEntity(Class<T> entityClass,Map<String,Object> fieldMap){
		
		if(MapUtils.isEmpty(fieldMap)){
			LOGGER.error("can not insert entity fieldMap is empty!!!!");
			return false;
		}
		
		String sql = " intsert into " + getTableName(entityClass);
		StringBuilder columns = new StringBuilder("(");
		StringBuilder values = new StringBuilder("(");
		for(String fieldName : fieldMap.keySet()){
			columns.append(fieldName).append(", ");
			values.append("?, ");
		}
		columns.replace(columns.lastIndexOf(", "), columns.length(), ")");
		values.replace(values.lastIndexOf(", "), values.length(), ")");
		sql = sql + columns + " values " + values;
		Object[] params = fieldMap.values().toArray();
		return executeUpdate(sql, params)==1;
		
	}
	
	
	/**
	 * 更新一个实体
	 * @param entityClass
	 * @param id
	 * @param fieldMap
	 * @return
	 */
	public static<T> boolean updateEntity(Class<T> entityClass,long id,Map<String,Object> fieldMap){
		if(MapUtils.isEmpty(fieldMap)){
			LOGGER.error("can not insert entity fieldMap is empty!!!!");
			return false;
		}
		
		String sql = " update " + getTableName(entityClass) + "  set ";
		StringBuilder columns = new StringBuilder();
		for(String fieldName : fieldMap.keySet()){
			columns.append(fieldName).append("=?, ");
		}
		
		sql = sql + columns.substring(0,columns.lastIndexOf(", ")) + " where id = ? ";
		
		List<Object> paramList = new ArrayList<Object>();
		paramList.addAll(fieldMap.values());
		paramList.add(id);
		Object[] params = paramList.toArray();
		
		return executeUpdate(sql, params)==1;
	}
	
	
	/**
	 * 删除一个实体
	 * @param entityClass
	 * @param id
	 * @return
	 */
	public static<T> boolean deleteEntity(Class<T> entityClass,long id){
		String sql = " delete from " + getTableName(entityClass) + " where id=?";
		return executeUpdate(sql, id)==1;
	}
	
	/**
	 * 执行SQL文件
	 * @param filepath
	 */
	public static void executeUpdateSqlFile(String filepath){
		if(StringUtils.isEmpty(filepath)){
			LOGGER.error("filepath can not be empty!!!!");
			return;
		}
		InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(filepath);
		BufferedReader bf = new BufferedReader(new InputStreamReader(is));
		try {
			String sql ;
			while((sql = bf.readLine())!=null){
				DatabaseHelper.executeUpdate(sql);
			}
		} catch (IOException e) {
			LOGGER.error("read sql file error!!!!");
			throw new RuntimeException(e);
		}
	}
}
